#[warn(unused_variables)]
use std::fs::File;
use std::io::{self, ErrorKind, Read};

// fn main() {
//     let greeting_file_result = File::open("hello.txt");
//     // 匹配不同的错误
//     let greeting_file = match greeting_file_result {
//         Ok(file) => file,
//         Err(error) => match error.kind() {
//             ErrorKind::NotFound => match File::create("hello.txt") {
//                 Ok(fc) => fc,
//                 Err(e) => panic!("Problem creating the file: {:?}", e),
//             },
//             other_error => {
//                 panic!("Problem opening the file: {:?}", other_error);
//             }
//         },
//     };
// }

// // 闭包和 unwrap_or_else
// fn main() {
//     let greeting_file = File::open("hello.txt").unwrap_or_else(|error| {
//         if error.kind() == ErrorKind::NotFound {
//             File::create("hello.txt").unwrap_or_else(|error| {
//                 panic!("Problem creating the file: {:?}", error);
//             })
//         } else {
//             panic!("Problem opening the file: {:?}", error);
//         }
//     });
// }

// // unwrap 和 expect,expect比较多，可以携带错误信息，便于调式
// fn main() {
//     // let greeting_file = File::open("hello.txt").unwrap();
//     let greeting_file =
//         File::open("hello.txt").expect("hello.txt should be included in this project");
// }

// // 传播错误
// fn main{
//     fn read_username_from_file()->Result<String, io::Error>{
//         let username_file_result = File::open("hello.txt");

//         let mut username_file = match username_file_result{
//             Ok(file) => file,
//             Err(e) => return Err(e),
//         };

//         let mut username = String::new();

//         match username_file.read_to_string(&mut username){
//             Ok(_) => Ok(username),
//             Err(e) => Err(e),
//         }
//     }
// }

// 传播错误简写 ?运算符
fn main{
    fn read_username_from_file()->Result<String, io::Error>{
        let mut username_file_file = File::open("hello.txt")?;
        let mut username = String::new();
        username_file.read_to_string(&mut username)?;
        Ok(username)
    }
}